﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System.Collections.Generic;
using System.Linq;
using FinPlusCommon;
using u = FinPlusUtility.Utility;

namespace FinPlusComponents
{
    public class QLAnalytics : FinPlusComponent
    {
        public override string[] TestStates { get { return new string[] { "TestString", "IsValid" }; } }
        public override IFunctions Adaptor { get { return _instrumentConn.Adaptor; } }
        public override string TestString { get { return Adaptor.ToString(); } }

        public ql QL { get { return _ql; } } 
        public string MarketName { get; private set; }
        public string CacheName { get; private set; }
        public string DiscountCurve { get; private set; }
        public int AsOf { get; private set; }
        public string BuySell { get; private set; }
        public IDictionary<string, string> Infos { get; private set; }
        public IDictionary<string, string> Controls { get; private set; }
        public IDictionary<string, int> Shocks { get; private set; }
        public string ControlString { get; set; }
        public bool HasControlString { get; set; }

        private enum Params { LevelUpdate, Request, Resend, Refresh, Shock }
        private readonly IFinPlusComp _instrumentConn;
        private readonly static ql _ql = new ql();
        private static IFunction _func;
        
        //construct
        public QLAnalytics(IFinPlusComp instruments, string marketName, string cacheName, int asOf, string discountCurve, 
            string buySell, IDictionary<string, string> infos, IDictionary<string, string> controls, IDictionary<string, int> shocks) 
        {
            IsValid = true;
            _instrumentConn = instruments;
            MarketName = marketName;
            CacheName = cacheName;
            BuySell = buySell;
            DiscountCurve = discountCurve;
            AsOf = asOf;
            Infos =infos;
            Controls = controls;
            ControlString = string.Join(",", Controls.Select(f => f.Key).ToArray());
            HasControlString = !string.IsNullOrEmpty(ControlString);
            Shocks = shocks;

            lock (QL)
                QL.MarketSet(MarketName, AsOf);

            if (_func == null) 
                _func = new Function("QL", "ql") { Object = QL, Type = QL.GetType() };
        }

        //common control interface
        public override void Dispose() 
        {
            if (_instrumentConn != null)
                _instrumentConn.Dispose();
        }

        public string InvokeMethod(IFunction func, u.Env env, IList<string> exclude = null)
        {
            var res = FinPlusDInject.Get.InvokeMethod(func, _func, exclude);
            return res.ToString();
        }
    }
}
